from rest_framework import status, permissions
from rest_framework.decorators import api_view, permission_classes
from rest_framework.response import Response
from django.shortcuts import get_object_or_404
from django.utils import timezone
from decimal import Decimal
import logging

from .models import Portfolio, StopLossSetting, Product
from .serializers import StopLossSettingSerializer
from .stop_loss_engine import StopLossEngine

logger = logging.getLogger(__name__)

@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def create_stop_loss(request):
    """
    创建止损设置
    
    POST /api/portfolios/stop-loss/create/
    {
        "portfolio_id": 1,
        "product_id": 1,
        "strategy_type": "fixed_ratio",
        "stop_loss_ratio": 0.1,
        "purchase_price": 100.0,
        "auto_execute": true
    }
    """
    try:
        data = request.data
        portfolio_id = data.get('portfolio_id')
        product_id = data.get('product_id')
        
        # 验证投资组合权限
        portfolio = get_object_or_404(Portfolio, id=portfolio_id, user=request.user)
        product = get_object_or_404(Product, id=product_id)
        
        # 准备策略数据
        strategy_data = {
            'strategy_type': data.get('strategy_type'),
            'stop_loss_ratio': Decimal(str(data.get('stop_loss_ratio', 0))) if data.get('stop_loss_ratio') else None,
            'purchase_price': Decimal(str(data.get('purchase_price', 0))) if data.get('purchase_price') else None,
            'trailing_distance': Decimal(str(data.get('trailing_distance', 0))) if data.get('trailing_distance') else None,
            'technical_indicator': data.get('technical_indicator'),
            'indicator_params': data.get('indicator_params'),
            'auto_execute': data.get('auto_execute', False),
            'status': 'active'
        }
        
        # 使用止损引擎创建设置
        engine = StopLossEngine()
        result = engine.create_stop_loss_setting(portfolio_id, product_id, strategy_data)
        
        if result['success']:
            # 获取创建的设置详情
            setting = StopLossSetting.objects.get(id=result['setting_id'])
            serializer = StopLossSettingSerializer(setting)
            
            return Response({
                'success': True,
                'message': '止损设置创建成功',
                'data': serializer.data
            }, status=status.HTTP_201_CREATED)
        else:
            return Response({
                'success': False,
                'error': result['error']
            }, status=status.HTTP_400_BAD_REQUEST)
            
    except Exception as e:
        logger.error(f"创建止损设置失败: {e}")
        return Response({
            'success': False,
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def list_stop_loss(request):
    """
    获取用户的止损设置列表
    
    GET /api/portfolios/stop-loss/list/
    """
    try:
        portfolio_id = request.GET.get('portfolio_id')
        
        # 构建查询条件
        queryset = StopLossSetting.objects.filter(
            portfolio__user=request.user
        ).select_related('portfolio', 'product')
        
        if portfolio_id:
            queryset = queryset.filter(portfolio_id=portfolio_id)
        
        # 按状态和创建时间排序
        settings = queryset.order_by('-created_at')
        
        serializer = StopLossSettingSerializer(settings, many=True)
        
        return Response({
            'success': True,
            'data': serializer.data,
            'count': len(serializer.data)
        })
        
    except Exception as e:
        logger.error(f"获取止损设置列表失败: {e}")
        return Response({
            'success': False,
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['PUT'])
@permission_classes([permissions.IsAuthenticated])
def update_stop_loss(request, setting_id):
    """
    更新止损设置
    
    PUT /api/portfolios/stop-loss/{setting_id}/update/
    """
    try:
        setting = get_object_or_404(
            StopLossSetting, 
            id=setting_id, 
            portfolio__user=request.user
        )
        
        # 只允许更新激活状态的设置
        if setting.status != 'active':
            return Response({
                'success': False,
                'error': '只能更新激活状态的止损设置'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        data = request.data
        
        # 更新允许的字段
        if 'stop_loss_ratio' in data:
            setting.stop_loss_ratio = Decimal(str(data['stop_loss_ratio']))
        if 'trailing_distance' in data:
            setting.trailing_distance = Decimal(str(data['trailing_distance']))
        if 'indicator_params' in data:
            setting.indicator_params = data['indicator_params']
        if 'auto_execute' in data:
            setting.auto_execute = data['auto_execute']
        
        setting.save()
        
        serializer = StopLossSettingSerializer(setting)
        
        return Response({
            'success': True,
            'message': '止损设置更新成功',
            'data': serializer.data
        })
        
    except Exception as e:
        logger.error(f"更新止损设置失败: {e}")
        return Response({
            'success': False,
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['DELETE'])
@permission_classes([permissions.IsAuthenticated])
def delete_stop_loss(request, setting_id):
    """
    删除止损设置
    
    DELETE /api/portfolios/stop-loss/{setting_id}/delete/
    """
    try:
        setting = get_object_or_404(
            StopLossSetting, 
            id=setting_id, 
            portfolio__user=request.user
        )
        
        # 将状态设置为已取消而不是删除记录
        setting.status = 'cancelled'
        setting.save()
        
        return Response({
            'success': True,
            'message': '止损设置已取消'
        })
        
    except Exception as e:
        logger.error(f"删除止损设置失败: {e}")
        return Response({
            'success': False,
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def check_stop_loss(request):
    """
    手动检查止损条件
    
    POST /api/portfolios/stop-loss/check/
    {
        "portfolio_id": 1  // 可选，不提供则检查用户所有投资组合
    }
    """
    try:
        portfolio_id = request.data.get('portfolio_id')
        
        engine = StopLossEngine()
        
        # 检查止损条件
        triggered_stop_losses = engine.check_all_stop_loss_conditions()
        
        # 过滤用户相关的触发结果
        user_triggered = {
            'fixed_ratio': [],
            'trailing': [],
            'technical': []
        }
        
        for strategy_type, triggers in triggered_stop_losses.items():
            for trigger in triggers:
                setting = trigger['setting']
                if setting.portfolio.user == request.user:
                    if not portfolio_id or setting.portfolio.id == int(portfolio_id):
                        user_triggered[strategy_type].append({
                            'setting_id': setting.id,
                            'portfolio_id': setting.portfolio.id,
                            'product_code': setting.product.code,
                            'product_name': setting.product.name,
                            'strategy_type': setting.strategy_type,
                            'current_price': float(trigger['current_price']),
                            'trigger_reason': trigger['trigger_reason']
                        })
        
        # 统计触发数量
        total_triggered = sum(len(triggers) for triggers in user_triggered.values())
        
        return Response({
            'success': True,
            'message': f'检查完成，发现 {total_triggered} 个触发的止损条件',
            'data': {
                'triggered_count': total_triggered,
                'triggered_stop_losses': user_triggered
            }
        })
        
    except Exception as e:
        logger.error(f"检查止损条件失败: {e}")
        return Response({
            'success': False,
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def trigger_stop_loss(request, setting_id):
    """
    手动触发止损
    
    POST /api/portfolios/stop-loss/{setting_id}/trigger/
    {
        "current_price": 95.0,
        "trigger_reason": "手动触发"
    }
    """
    try:
        setting = get_object_or_404(
            StopLossSetting, 
            id=setting_id, 
            portfolio__user=request.user
        )
        
        if setting.status != 'active':
            return Response({
                'success': False,
                'error': '只能触发激活状态的止损设置'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        current_price = Decimal(str(request.data.get('current_price', 0)))
        trigger_reason = request.data.get('trigger_reason', '手动触发')
        
        if current_price <= 0:
            return Response({
                'success': False,
                'error': '请提供有效的当前价格'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        engine = StopLossEngine()
        result = engine.trigger_stop_loss(setting, current_price, trigger_reason)
        
        if result['success']:
            return Response({
                'success': True,
                'message': '止损触发成功',
                'data': result
            })
        else:
            return Response({
                'success': False,
                'error': result.get('error', '触发止损失败')
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
            
    except Exception as e:
        logger.error(f"触发止损失败: {e}")
        return Response({
            'success': False,
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

@api_view(['GET'])
@permission_classes([permissions.IsAuthenticated])
def stop_loss_statistics(request):
    """
    获取止损统计信息
    
    GET /api/portfolios/stop-loss/statistics/
    """
    try:
        user_settings = StopLossSetting.objects.filter(
            portfolio__user=request.user
        )
        
        # 统计各种状态的数量
        stats = {
            'total': user_settings.count(),
            'active': user_settings.filter(status='active').count(),
            'triggered': user_settings.filter(status='triggered').count(),
            'executed': user_settings.filter(status='executed').count(),
            'cancelled': user_settings.filter(status='cancelled').count()
        }
        
        # 按策略类型统计
        strategy_stats = {
            'fixed_ratio': user_settings.filter(strategy_type='fixed_ratio').count(),
            'trailing': user_settings.filter(strategy_type='trailing').count(),
            'technical': user_settings.filter(strategy_type='technical').count()
        }
        
        # 最近触发的止损
        recent_triggered = user_settings.filter(
            status__in=['triggered', 'executed']
        ).order_by('-triggered_at')[:5]
        
        recent_data = []
        for setting in recent_triggered:
            recent_data.append({
                'id': setting.id,
                'portfolio_name': setting.portfolio.name,
                'product_name': setting.product.name,
                'strategy_type': setting.strategy_type,
                'status': setting.status,
                'triggered_at': setting.triggered_at.isoformat() if setting.triggered_at else None
            })
        
        return Response({
            'success': True,
            'data': {
                'status_statistics': stats,
                'strategy_statistics': strategy_stats,
                'recent_triggered': recent_data
            }
        })
        
    except Exception as e:
        logger.error(f"获取止损统计失败: {e}")
        return Response({
            'success': False,
            'error': str(e)
        }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)